/**
 * 
 */
package com.umakr.ax.scheduler.job;

import com.umakr.ax.scheduler.TaskScheduled;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.context.ApplicationContext;

/**
 * 默认调度(非阻塞)
 * @author gx
 * @since 2017/6/1
 */
public class BaseJob implements Job {
	protected final Log logger = LogFactory.getLog(this.getClass());

	@Override
	public void execute(JobExecutionContext context) throws JobExecutionException {
		long start = System.currentTimeMillis();
		JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
		String taskType = jobDataMap.getString("taskType");
		String targetObject = jobDataMap.getString("targetObject");
		String targetMethod = jobDataMap.getString("targetMethod");
		logger.info(String.format("定时任务开始执行: [%s.%s]", targetObject, targetMethod));
		try {
			ApplicationContext applicationContext = (ApplicationContext) context.getScheduler().getContext()
					.get("applicationContext");
			if (TaskScheduled.TaskType.LOCAL.equals(taskType)) {
				Object refer = applicationContext.getBean(targetObject);
				refer.getClass().getDeclaredMethod(targetMethod).invoke(refer);
			}
			double time = (System.currentTimeMillis() - start) / 1000.0;
			logger.info(String.format("定时任务[%s.%s]用时：%ss", targetObject, targetMethod, time));
		} catch (Exception e) {
			throw new JobExecutionException(e.getCause());
		}
	}
}
